<template>
  <div class="role-management-container">
    <el-card>
      <div class="toolbar">
        <el-button type="success" :icon="Plus" @click="handleAddRole">添加新角色</el-button>
      </div>

  <el-table :data="roleList" border style="width: 100%" size="small" class="compact-table">
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-wrap">
              <p v-if="!row.rights || row.rights.length === 0">暂无权限</p>
              <el-row v-else>
                <el-col :span="24" v-for="right1 in row.rightsTree" :key="right1.right_id" class="level1">
                  <el-tag size="small">{{ right1.right_name }}</el-tag>
                  <el-row>
                    <el-col :span="22" :offset="2">
                      <el-tag v-for="right2 in right1.children" :key="right2.right_id" type="success" class="level2" size="small">
                        {{ right2.right_name }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="role_name" label="角色名称" min-width="160" />
        <el-table-column label="权限数量" width="120" align="center">
          <template #default="{ row }">
            <span class="badge badge--blue">{{ row.rights?.length || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handlePermissionAssign(row)">权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" title="添加新角色" width="30%">
      <el-form :model="newRoleForm">
        <el-form-item label="角色名称">
          <el-input v-model="newRoleForm.role_name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="permissionDialogVisible" title="权限分配" width="60%">
      <el-tree
        :data="allRights"
        :props="{ label: 'right_name', children: 'children' }"
        show-checkbox
        node-key="right_id"
        :default-checked-keys="currentRoleRights"
        ref="tree"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPermissionAssign">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { getRoleListAPI, addRoleAPI, updateRolePermissionAPI, getRightListAPI } from '@/api/root/role'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const roleList = ref([])
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const newRoleForm = ref({
  role_name: ''
})
const allRights = ref([])
const currentRoleRights = ref([])
const currentRole = ref(null)
const tree = ref(null)

const buildTree = (list, parentId = 0) => {
  return list
    .filter((item) => item.parent_id === parentId)
    .map((item) => ({
      ...item,
      children: buildTree(list, item.right_id)
    }))
}

const fetchRoleList = async () => {
  const res = await getRoleListAPI()
  if (res) {
    roleList.value = res.map(role => ({
      ...role,
      rightsTree: buildTree(role.rights)
    }))
  }
}

const fetchAllRights = async () => {
  const res = await getRightListAPI()
  if (res) {
    allRights.value = buildTree(res)
  }
}

const handleAddRole = () => {
  newRoleForm.value.role_name = ''
  dialogVisible.value = true
}

const confirmAddRole = async () => {
  if (!newRoleForm.value.role_name) {
    ElMessage.warning('请输入角色名称')
    return
  }
  await addRoleAPI(newRoleForm.value)
  dialogVisible.value = false
  await fetchRoleList()
}

const handlePermissionAssign = (role) => {
  currentRole.value = role
  const getLeafKeys = (rights) => {
    const keys = []
    rights.forEach(r => {
      if (!r.children || r.children.length === 0) {
        keys.push(r.right_id)
      } else {
        keys.push(...getLeafKeys(r.children))
      }
    })
    return keys
  }
  currentRoleRights.value = getLeafKeys(role.rightsTree)
  permissionDialogVisible.value = true
  nextTick(() => {
    if (tree.value) {
      tree.value.setCheckedKeys(currentRoleRights.value)
    }
  })
}

const confirmPermissionAssign = async () => {
  const checkedKeys = tree.value.getCheckedKeys(false)
  const halfCheckedKeys = tree.value.getHalfCheckedKeys()
  const allChecked = [...checkedKeys, ...halfCheckedKeys]

  const allRightIds = []
  const flattenTree = (nodes) => {
    nodes.forEach(node => {
      allRightIds.push(node.right_id)
      if (node.children) {
        flattenTree(node.children)
      }
    })
  }
  flattenTree(allRights.value)

  const permissionsToUpdate = allRightIds.map(rightId => ({
    role_id: currentRole.value.role_id,
    right_id: rightId,
    right_function: allChecked.includes(rightId) ? 1 : 0
  }))

  for (const p of permissionsToUpdate) {
    await updateRolePermissionAPI(p)
  }

  permissionDialogVisible.value = false
  await fetchRoleList()
  ElMessage.success('权限分配成功')
}

onMounted(() => {
  fetchRoleList()
  fetchAllRights()
})
</script>

<style scoped>
.role-management-container {
  padding: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  box-shadow: none;
  border: none;
  background: transparent;
}
.el-card :deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 0;
}
.el-card :deep(.el-card__header) {
  border-bottom: none;
  padding-bottom: 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.toolbar {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 8px;
}
.expand-wrap { padding: 6px 10px; }
.level1 { border-bottom: 1px solid #f2f2f2; padding: 6px 0; }
.level1:last-child {
  border-bottom: none;
}
.level2 {
  margin: 4px;
}
/* 对齐到示例图尺寸：字号12、行高≈28px、标签≈20px */
.compact-table :deep(.el-table__cell) { padding: 2px 8px !important; }
.compact-table :deep(.el-table__header th .cell),
.compact-table :deep(.el-table__body td .cell) { padding: 0 !important; font-size: 12px; line-height: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.compact-table :deep(.el-table__header tr) { height: 28px; }
.compact-table :deep(.el-table__body tr) { height: 32px; }
.compact-table :deep(.el-tag--small) { font-size: 12px; line-height: 18px; height: 20px; padding: 0 6px; margin-right: 6px; }

/* 弹窗内树形权限列表的紧凑化 */
:deep(.el-dialog) :deep(.el-tree-node__content) {
  height: 20px;
  line-height: 20px;
  padding: 0 4px;
  font-size: 11px;
}
</style>
